<template>
  <div class="form-setting-group form-limit-word-setting">
    <el-checkbox :value="field.setting.isLimitWord" @input="updateLimitWord" :true-label="1" :false-label="0">
      {{$t('common.base.limitWord')}}
      <el-tooltip :content="$t('common.form.tip.limitWordTips')" placement="top">
        <i class="iconfont icon-question"></i>
      </el-tooltip>
    </el-checkbox>
    <div class="form-setting-item limit-word-setting-item" v-if="field.setting.isLimitWord">
      <el-input v-model="limitWordMin" :min="min" :max="max" type="number" @change="updateLimitWordMin" :placeholder="min"></el-input>
      <span class="limit-word-range">~</span>
      <el-input v-model="limitWordMax" :min="min" :max="max" type="number" @change="updateLimitWordMax" :placeholder="max"></el-input>
    </div>
  </div>
</template>

<script>
import { FORM_FIELD_TEXT_MAX_LENGTH, FORM_FIELD_TEXTAREA_MAX_LENGTH } from '@src/model/const/Number.ts';
/* props */
import { settingProps } from '@src/component/form/components/props';

export default {
  name: 'form-limit-word-setting',
  props: {
    ...settingProps,
    disabled: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      min: 1,
      limitWordMin: this.field.setting.limitWordMin,
      limitWordMax: this.field.setting.limitWordMax,
    }
  },
  computed:{
    max(){
      if(this.field?.formType === 'textarea'){
        return FORM_FIELD_TEXTAREA_MAX_LENGTH
      }
      return FORM_FIELD_TEXT_MAX_LENGTH
    }
  },
  methods: {
    updateLimitWord(value) {
      this.update(value, 'isLimitWord')
    },
    handleValue(value, type) {
      if (value) {
        value = parseInt(value)
      }
      if (value !== '' && value < this.min) value = this.min
      if (value > this.max) value = this.max
      if (this.limitWordMax && this.limitWordMin > this.limitWordMax) {
        type == 'max' ? value = this.limitWordMin : value = this.limitWordMax
      }
      return value
    },
    updateLimitWordMin(value) {
      this.limitWordMin = this.handleValue(value, 'min')
      this.update(this.limitWordMin, 'limitWordMin')
    },
    updateLimitWordMax(value) {
      this.limitWordMax = this.handleValue(value, 'max')
      this.update(this.limitWordMax, 'limitWordMax')
    },
    update(value, prop) {
      this.$emit('input', value, prop, true)
    }
  }
}
</script>
<style lang="scss" scoped>
.form-limit-word-setting {
  .limit-word-setting-item {
    display: flex;
    align-items: center;
    padding-top: 8px;
    .limit-word-range {
      padding: 0 8px;
    }
  }
}
</style>